<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas{
      background-color: black;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="1000" height="800"></canvas>
  <script>
    /** @type {HTMLCanvasElement} */
    var canvas=document.querySelector("#canvas")

    var ctx=canvas.getContext("2d")
    function Ball(x,y,dx,dy,radius,color){//构造函数
      this.x=x
      this.y=y
      this.dx=dx
      this.dy=dy
      this.radius=radius
      this.color=color
      this.update=function(){
        if(this.x+this.radius>=canvas.width||this.x-this.radius<=0){
          this.dx=-this.dx
        }
        else if(this.y+this.radius>=canvas.height||this.y-this.radius<=0){
          this.dy=-this.dy
        }
        this.x+=this.dx
        console.log(this.x);
        this.y+=this.dy
        // this.draw()
      }
      this.draw=function(){
        ctx.beginPath()
        ctx.save()
        ctx.arc(this.x,this.y,this.radius,0,Math.PI*2)
        ctx.fillStyle=this.color
        ctx.fill()
        ctx.restore()
        ctx.closePath()
        this.update()
      }
      
    }
    let ballArray=[]
    for(var i=0;i<200;i++){
      let radius=Math.random()*10
      let x=Math.random()*canvas.width
      let y=Math.random()*canvas.height
      let dx=(Math.random()-0.5)*5
      // let dx=Math.random()*2
      // let dy=Math.random()*2
      let dy=(Math.random()-0.5)*2
      let color="rgb("+Math.floor(Math.random() *256)+","+Math.floor(Math.random() *256)+","+Math.floor(Math.random() *256)+")";
      ballArray.push(new Ball(x,y,dx,dy,radius,color))
    }
    // let ball=new Ball(300,300,5,5,10,"red")
    function qou(){
      ctx.clearRect(0,0,canvas.width,canvas.height)
      // ball.update()
      for(var i=0;i<ballArray.length;i++){
        // ballArray[i].update()
        ballArray[i].draw()
      }
      // ctx.beginPath()
      //   ctx.save();
      //   ctx.fillStyle="rgba(0,0,0,.1)"
      //   ctx.fillRect(0,0,canvas.width,canvas.height);
      //   ctx.restore();
      //   ctx.closePath()
      // ctx.fillStyle="rgba(0,0,0,.1)"
      // // ctx.rect(0,0,1000,800)
      // ctx.fill()
      requestAnimationFrame(qou)
    }
    qou()
  </script>
</body>
</html>